import 'dart:async';

import 'package:flutter/services.dart';
import 'package:meta/meta.dart';

import 'enums.dart';
import 'flutter_plus_platform_interface.dart';
import 'utils.dart';

/// 使用方法通道的[FlutterPlatform]的实现。
class MethodChannelFlutter extends FlutterPlatform {
  /// 用于与本机平台交互的方法通道。
  @visibleForTesting
  MethodChannel methodChannel =
      const MethodChannel('dev.fluttercommunity.plus/connectivity');

  /// 用于接收来自本机平台的ConnectivityResult更改的事件通道。
  @visibleForTesting
  EventChannel eventChannel =
      const EventChannel('dev.fluttercommunity.plus/connectivity_status');

  Stream<FlutterResult>? _onConnectivityChanged;

  /// 每当连接状态改变时触发。
  @override
  Stream<FlutterResult> get onConnectivityChanged {
    _onConnectivityChanged ??= eventChannel
        .receiveBroadcastStream()
        .map((dynamic result) => result.toString())
        .map(parseConnectivityResult);
    return _onConnectivityChanged!;
  }

  @override
  Future<FlutterResult> checkConnectivity() {
    return methodChannel
        .invokeMethod<String>('check')
        .then((value) => parseConnectivityResult(value ?? ''));
  }
}
